﻿using Microsoft.Owin;
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace ldhWebApiWF
{
    public class LoggingMiddleware : OwinMiddleware
    {
        [DllImport("Kernel32.dll")]
        static extern bool QueryPerformanceCounter(ref long count);
        [DllImport("Kernel32.dll")]
        static extern bool QueryPerformanceFrequency(ref long count);   


        public LoggingMiddleware(OwinMiddleware next) : base(next) { }

        public async override Task Invoke(IOwinContext context)
        {
            //enable corss domain ajax access
            if (context.Request.Method == "OPTIONS")
            {
                await Next.Invoke(context);
                return;
            }

            var start = DateTime.Now;
            await Next.Invoke(context);
            var exptime = DateTime.Now.Subtract(start).TotalMilliseconds.ToString("f0") + "ms";
            if (Program.form.lb_msg.Items.Count >= Program.form.logRecords)
            {
                Program.form.lb_msg.Items.Clear();
            }
            Program.form.lb_msg.Items.Insert(0, context.Request.Method + " " + context.Request.Uri 
                + " " + context.Response.StatusCode + " " + exptime);
        }
    }
}
